<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        class Scheduler {
            constructor(conut) {
                this.count = conut // 同时运行的最大任务数
                this.runCount = 0 // 运行中的任务数
                this.taskQueue = []
            }

            // 运行任务
            async runTask(task, resolve, reject) {
                this.runCount++
                await task().then(resolve, reject)
                this.runCount--
                if (this.taskQueue.length > 0) {
                    let item = this.taskQueue.shift()
                    this.runTask(item.fun, item.resolve, item.reject)
                }
            }

            add(promiseCreator) {
                return new Promise((resolve, reject) => {
                    if (this.runCount >= this.count) {
                        this.taskQueue.push({ fun: promiseCreator, resolve, reject })
                    } else {
                        this.runTask(promiseCreator, resolve, reject)
                    }
                })
            }
        }


        const timeout = (time) => new Promise(resolve => {
            setTimeout(resolve, time)
        })

        const scheduler = new Scheduler(2)
        const addTask = (time, order) => {
            scheduler.add(() => timeout(time)).then(() => console.log(order))
        }

        addTask(1000, '1')
        addTask(500, '2')
        addTask(300, '3')
        addTask(400, '4')

        // 打印顺序是：2 3 1 4
    </script>
</body>

</html>